package com.itheima.restkeeper.face;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.BrandFace;
import com.itheima.restkeeper.enums.BrandEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Brand;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.BrandVo;
import com.itheima.restkeeper.service.IBrandService;
import com.itheima.restkeeper.utils.BeanConv;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BrandFaceImpl.java
 * @Description 品牌dubbo接口定义实现
 */
@DubboService(version = "${dubbo.application.version}",timeout = 5000,
    methods ={
        @Method(name = "findBrandVoPage",retries = 2),
        @Method(name = "createBrand",retries = 0),
        @Method(name = "updateBrand",retries = 0),
        @Method(name = "deleteBrand",retries = 0)
    })
@Slf4j
public class BrandFaceImpl implements BrandFace {

    @Autowired
    IBrandService brandService;

    @DubboReference(version = "${dubbo.application.version}",check = false)
    AffixFace affixFace;


    /**
     * 分页查询品牌信息
     * @param brandVo 查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return
     * @throws ProjectException
     */
    @Override
    public Page<BrandVo> findBrandVoPage(BrandVo brandVo,
                                         int pageNum,
                                         int pageSize) throws ProjectException{
        try {
            //查询Page<Brand>图片分页
            Page<Brand> page = brandService.findBrandVoPage(brandVo, pageNum, pageSize);
            //转化Page<Brand>为Page<BrandVo>
            //创建一个vo对象的page
            Page<BrandVo> voPage = new Page<>();
            BeanConv.toBean(page,voPage);
            //转换List<Brand>为 List<BrandVo>
            List<Brand> brandList = page.getRecords();
            List<BrandVo> brandVoList = BeanConv.toBeanList(brandList, BrandVo.class);
            //处理附件
            if (!EmptyUtil.isNullOrEmpty(voPage)&&!EmptyUtil.isNullOrEmpty(brandVoList)) {
                //遍历vo集合
                brandVoList.forEach(brandVo1 -> {
                    //查询出品牌的附件信息
                    List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(brandVo.getId());
                    //判断集合是否为空
                    if (!EmptyUtil.isNullOrEmpty(affixVoList)) {
                        //不为空将第一个元素设置到vo对象中
                        brandVo1.setAffixVo(affixVoList.get(0));
                    }
                });
            }
            //将数据设置到页面对象中
            voPage.setRecords(brandVoList);
            //返回结果
            return voPage;
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }

    /**
     * 新增品牌
     * @param brandVo 对象信息
     * @return
     * @throws ProjectException
     */
    @Override
    public BrandVo createBrand(BrandVo brandVo) throws ProjectException{
        try {
            //执行保存
            Brand brand = brandService.createBrand(brandVo);
            //将得到的brand对象转化为vo对象
            BrandVo result = BeanConv.toBean(brand, BrandVo.class);
            //绑定附件
            if (!EmptyUtil.isNullOrEmpty(result)) {
                //不为空
                affixFace.bindBusinessId(AffixVo.builder()
                        .businessId(result.getId())
                        .id(brandVo.getAffixVo().getId())
                        .build());
            }
            //为空的话,则设置affixVo对象
            brandVo.setAffixVo(AffixVo.builder()
                    //设置地址
                    .pathUrl(brandVo.getAffixVo().getPathUrl())
                    //设置品牌id
                    .businessId(brandVo.getId())
                    //设置附件id
                    .id(brandVo.getAffixVo().getId()).build());
            return result;
        } catch (Exception e) {
            log.error("保存品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.CREATE_FAIL);
        }
    }

    /**
     * 修改品牌
     * @param brandVo 对象信息
     * @return
     * @throws ProjectException
     */
    @Override
    public Boolean updateBrand(BrandVo brandVo)throws ProjectException {
        try {
            //执行修改
            Boolean result = brandService.updateBrand(brandVo);
            //修改对应的附件图片（先删除后添加）
            //判断结果是否成功
            if (result) {
                //查出附件信息
                List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(brandVo.getId());
                //将其中的id拿出来
                List<Long> ids = affixVos.stream().map(AffixVo::getId).collect(Collectors.toList());
                //判断id集合中是否包含修改的附件id
                if (!ids.contains(brandVo.getAffixVo().getId())) {
                    //不包含的话说明修改了图片
                    //删除图片
                    result=affixFace.deleteAffixVoByBusinessId(brandVo.getId());
                    //绑定新图片
                    affixFace.bindBusinessId(AffixVo.builder()
                            .businessId(brandVo.getId())
                            .id(brandVo.getAffixVo().getId())
                            .build());
                }
            }
            //返回最终结果
            return result;
        } catch (Exception e) {
            log.error("修改品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_FAIL);
        }

    }

    /**
     * 批量删除品牌
     * @param checkedIds 选择中对象Ids
     * @return
     * @throws ProjectException
     */
    @Override
    public Boolean deleteBrand(String[] checkedIds) throws ProjectException{
        try {
            //执行删除
            Boolean result = brandService.deleteBrand(checkedIds);
            if (result) {
                //删除图片
                for (String checkedId : checkedIds) {
                    //执行删除图片操作
                    result = affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
                }
            }
            //返回最终结果
            return result ;
        } catch (Exception e) {
            log.error("删除品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.DELETE_FAIL);
        }
    }

    /**
     * 通过品牌id查询品牌信息
     * @param brandId 选择对象信息Id
     * @return
     * @throws ProjectException
     */
    @Override
    public BrandVo findBrandByBrandId(Long brandId)throws ProjectException {
        try {
            //执行查询,返回最终结果
            return BeanConv.toBean(brandService.getById(brandId),BrandVo.class);
        } catch (Exception e) {
            log.error("查找品牌所有品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.SELECT_BRAND_FAIL);
        }
    }

    /**
     * 查询品牌下拉列表
     * @return
     * @throws ProjectException
     */
    @Override
    public List<BrandVo> findBrandVoList()throws ProjectException {
        try {
            //查询品牌下拉列表
            return BeanConv.toBeanList(brandService.findBrandVoList(),BrandVo.class);
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }
}
